import React from 'react';
import PropTypes from 'prop-types';
import { ButtonToolbar, ToggleButtonGroup, ToggleButton } from 'react-bootstrap';

export default class CheckButtons extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.defaultValue,
    };
  }

  onChange(v) {
    this.setState({ value: v });
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(v);
    }
  }

  render() {
    const { type, data, name, className, style } = this.props;
    const buttons = data.map(e => (
      <ToggleButton value={e.value} key={e.value}>{e.text}</ToggleButton>
    ));
    return (
      <ButtonToolbar className={className} style={style} >
        <ToggleButtonGroup
          type={type}
          name={name}
          value={this.state.value}
          onChange={v => this.onChange(v)}
        >
          {buttons}
        </ToggleButtonGroup>
      </ButtonToolbar>
    );
  }
}

CheckButtons.defaultProps = {
  type: 'checkbox',
  defaultValue: '',
  data: [],
};

CheckButtons.propTypes = {
  type: PropTypes.oneOf(['checkbox', 'radio']),
  defaultValue: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.array,
  ]),
  data: PropTypes.array,
};
